﻿namespace A2DFramework.OSGI.Helps
{
    using A2DFramework.OSGI.BundleContexts;
    using System;
    using System.Collections;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.Runtime.Serialization.Formatters;

    public class RemotingServiceHelper
    {
        public static void RegisterOSGIService(string requestServiceType, int prot, string serviceUri)
        {
            BundleContext current = BundleContext.Current;
            string moduleName = current.GetModuleName(requestServiceType);
            string dllName = current.GetDllName(requestServiceType);
            RemotingConfiguration.RegisterWellKnownServiceType(TypeHelper.ParseType(moduleName, dllName, requestServiceType), serviceUri, WellKnownObjectMode.SingleCall);
            BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
            BinaryClientFormatterSinkProvider clientSinkProvider = new BinaryClientFormatterSinkProvider();
            serverSinkProvider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary properties = new Hashtable();
            properties["port"] = prot;
            TcpChannel chnl = new TcpChannel(properties, clientSinkProvider, serverSinkProvider);
            ChannelServices.RegisterChannel(chnl);
        }

        public static void RegisterOSGIService(string requestServiceType, string serviceProviderType, int prot, string serviceUri)
        {
            BundleContext current = BundleContext.Current;
            string moduleName = current.GetModuleName(requestServiceType);
            string serviceProviderDllName = current.GetServiceProviderDllName(requestServiceType);
            RemotingConfiguration.RegisterWellKnownServiceType(TypeHelper.ParseType(moduleName, serviceProviderDllName, serviceProviderType), serviceUri, WellKnownObjectMode.SingleCall);
            BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
            BinaryClientFormatterSinkProvider clientSinkProvider = new BinaryClientFormatterSinkProvider();
            serverSinkProvider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary properties = new Hashtable();
            properties["port"] = prot;
            TcpChannel chnl = new TcpChannel(properties, clientSinkProvider, serverSinkProvider);
            ChannelServices.UnregisterChannel(ChannelServices.GetChannel(chnl.ChannelName));
            ChannelServices.RegisterChannel(chnl);
        }
    }
}

